# coding=utf-8
"""
Copyright 2019-2020 Fang Jin Biao

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# @Time    : 2020/7/19 19:35
# @Author  : Fang Jin Biao
# @Email   : 215466914@qq.com
# @File    : knowledge_acquire_api.py
# @Project : SnowAdminWeb
import datetime

from flask import Blueprint, request, session,g
from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser

from webapp.config.api_utils import build_params, oper_log, check_auth
from webapp.dto_mapper import knowledge_acquire_page_fields,knowledge_acquire_fields
from webapp.schema import knowledgeAcquireSchema
from webapp.service.knowledge_acquire_service import KnowledgeAcquireService
from webapp.tools import format_date, download_excel_knowledge, connect_server
from collections import OrderedDict
import json
knowledge_acquire_app = Blueprint('knowledge_acquire', __name__, url_prefix='/api/knowledgeAcquire')
knowledge_acquire_api = Api(knowledge_acquire_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('parent_id', location='json', type=int, trim=True, required=False)
parser.add_argument('title', location='json', type=str, trim=True, required=True)
parser.add_argument('think', location='json', type=str, trim=True, required=False)
parser.add_argument('search_key_word', location='json', type=str, trim=True, required=False)
parser.add_argument('reference', location='json', type=str, trim=True, required=False)



@knowledge_acquire_api.resource('', '/')
class AppAPI(Resource):
    @oper_log('查询知识获取', request)
    @marshal_with(knowledge_acquire_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = build_params(params)
        data = json.loads(g.get("user"))
        user_id = data["id"]
        pagination = KnowledgeAcquireService.query_all(user_id=user_id,**params_dict)
        return pagination

    @oper_log('新增知识获取', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = knowledgeAcquireSchema()
        curr_data = schema.load(params, unknown="exclude")
        data = json.loads(g.get("user"))
        curr_data.user_id = data["id"]

        return KnowledgeAcquireService.create(curr_data=curr_data)

    @oper_log('修改知识获取', request)
    def put(self):
        parser_post = parser.copy()
        parser_post.parse_args()
        params = request.get_json()
        schema = knowledgeAcquireSchema()
        curr_data = schema.load(params, unknown="exclude")
        data = json.loads(g.get("user"))
        curr_data.user_id = data["id"]
        KnowledgeAcquireService.update(curr_data=curr_data)

    @oper_log('删除知识获取', request)
    def delete(self):
        ids = request.get_json()
        KnowledgeAcquireService.delete(ids=ids)

@knowledge_acquire_api.resource('/download')
class Downloadknowledge(Resource):
    @oper_log('导出知识获取数据', request)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = build_params(params)
        data = json.loads(g.get("user"))
        user_id = data["id"]
        pagination = KnowledgeAcquireService.query_all(user_id=user_id,**params_dict)
        contents = []
        reference_len=[]
        all_data=[]
        for items in pagination.items:
            all_data.append(items)
            for child in items.children:
                all_data.append(child)

        for items in all_data:
            data = OrderedDict()
            data["问题"] = items.title
            # data["思考过程"] = items.think
            search_key_word_str=""
            search_key_words = json.loads(items.search_key_word)
            for item in search_key_words:
                search_key_word_str += item + "\n"
            # data["关键字"] = search_key_word_str
            reference = json.loads(items.reference)
            total_len =0
            for item in reference:
                total_len+=len(item["results"])
            data["相关网站"] = reference
            reference_len.append(total_len)
            contents.append(data)

        return download_excel_knowledge(contents, reference_len,["title","publicationInfo","snippet","link","pdfUrl","doi","citedBy","year"])

@knowledge_acquire_api.resource('/downloadBySearch')
class downloadBySearch(Resource):
    @oper_log('导出知识获取关键词数据', request)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = build_params(params)
        _id = params_dict.get("id")
        index = params_dict.get("index")
        pagination = KnowledgeAcquireService.query_search_key(**params_dict)
        contents = []
        reference_len=[]
        for items in pagination.items:
            data = OrderedDict()
            data["问题"] = items.title
            reference = json.loads(items.reference)
            total_len =0
            reference_by_index=[]
            for key,item in enumerate(reference):
                if key == int(index):
                    reference_by_index.append(item)
                    total_len+=len(item["results"])
            data["相关网站"] = reference_by_index
            reference_len.append(total_len)
            contents.append(data)
        return download_excel_knowledge(contents, reference_len,["title","publicationInfo","snippet","link","pdfUrl","doi","citedBy","year"])

@knowledge_acquire_api.resource('/<int:_id>')
class GetServerById(Resource):
    @oper_log('根据ID查询知识获取', request)
    @marshal_with(knowledge_acquire_fields)
    def get(self, _id):
        data = json.loads(g.get("user"))
        user_id = data["id"]
        data = KnowledgeAcquireService.find_by_id(id=_id,user_id=user_id)
        return data


